package Controller;

import Dao.Impl.FileSqlOperationImpl;
import Utils.FileOperation;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

@WebServlet("/upload")
public class Servlet extends HttpServlet {
    FileOperation fileOperation;
    FileSqlOperationImpl fileSqlOperation;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        System.out.println("跳转成功");
        fileOperation = new FileOperation();
/*//        查看前段传入的数据流
       ServletInputStream inputStream=request.getInputStream();
        byte b[]=new byte[10*1024*1024];
        int read =inputStream.read(b);
        System.out.println(new String(b,0,read));
        inputStream.readLine(b,0,b.length);*/
        RequestContext ctx = new ServletRequestContext(request);
            int id =ctx.getInputStream().hashCode();
            System.out.println(id);
           fileOperation.setId(id);
//        判断上传的数据是否为多段(只有多段的数据，才是文件上传)
        if (ServletFileUpload.isMultipartContent(ctx)) {
//          创建FileItemFactory工厂实现类
            FileItemFactory itemFactory = new DiskFileItemFactory();

//            用于解析上传文件的工具类ServletFileUplod
            ServletFileUpload servletFileUpload = new ServletFileUpload(itemFactory);

//            查看文件上传编码
//            System.out.println("头部文件编码"+servletFileUpload.getHeaderEncoding());
//            设置文件上传的大小
            servletFileUpload.setSizeMax(10 * 1024 * 1024);//格式：字节，超出大小报错

//            解析上传数据，得到每一个表单
            try {
                List<FileItem> list = servletFileUpload.parseRequest(ctx);
                String suffix = null;
                for (FileItem item : list) {

                    System.out.println("item.getContentType\t"+item.getContentType()+"item.getName()\t"+item.getName()+"item.getSize()\t"+item.getSize());
                    fileOperation.setFileName(item.getName());
                    fileOperation.setSize(item.getSize());
//                循环判断每一个表单项,是普通类型还是上传的文件
                    try {
                        suffix = item.getName().substring(item.getName().lastIndexOf("."));
                        System.out.println("item:"+item);
                    } catch (Exception e) {
                        System.out.println("类型不符合");
                    }
                    System.out.println("文件类型"+suffix);
                    fileOperation.setFileType(suffix);

//                    限制文件类型
                    while (fileOperation.istType(suffix)) {
                        if (item.isFormField()) {
                            //普通表单项目
                            System.out.println("普通表单项的name属性值：" + item.getFieldName());
                            System.out.println("普通表单项的value值：" + item.getString("UTF-8"));
                            break;
                        } else {
//                        上传的文件
                            System.out.println("文件的name属性值：" + item.getFieldName());
                            System.out.println("上传的文件名：" + item.getName());
                            fileOperation.createDefultPath();
                            String filePath=fileOperation.getClassPath()+fileOperation.getUserPath();
                            System.out.println("filePath"+filePath);
                            fileOperation.creatServerFileName();
//                          文件写入服务器
                            item.write(fileOperation.storesFilePathDefult(filePath,fileOperation.getServerFileName()));
//                          文件插入数据库
                            fileSqlOperation=new FileSqlOperationImpl(fileOperation);
                            fileSqlOperation.insertFileInformation();
                            break;
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{

            }

        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
            ServletException, IOException {
        doGet(request, response);
    }
}
